package com.example.micrauth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.example.micrapi.feign.SysMenuServiceFeign;
import com.example.micrapi.feign.SysUserServiceFeign;
import com.example.micrapi.pojo.SysMenu;
import com.example.micrapi.pojo.SysRole;
import com.example.micrapi.pojo.SysUser;
import com.example.micrauth.domain.vo.LoginUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: TODO
 * @author: uu
 * @date: 2024/2/28 19:14
 * @version: 1.0
 */
@Service
@Slf4j
public class SysUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserServiceFeign sysUserServiceFeign;
    @Autowired
    private SysMenuServiceFeign sysMenuServiceFeign;
    /**
     * @description: 根据用户名查询用户
     * @author: uu
     * @date: 2024/2/28 19:18
     * @version: 1.0
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO 验证账号类型
        int type = 0;
        SysUser sysUser = sysUserServiceFeign.findByUserName(username, type);
        log.info("springSecurity find sysUser = {}", sysUser);

        LoginUserVO loginUserVO = new LoginUserVO();

        if(ObjectUtil.isNotNull(sysUser)) {
            List<SysRole> roleList = sysUser.getRoleList();
            log.info("springSecurity find roleList = {}", roleList);
            List<Integer> roleIds = roleList.stream().map(SysRole::getId).collect(Collectors.toList());
            log.info("springSecurity find roleIds = {}", roleIds);

            // 查询所有菜单
            List<SysMenu> menus = sysMenuServiceFeign.findByRoleIds(roleIds);
            List<String> codes = menus.stream().map(SysMenu::getCode).collect(Collectors.toList());
            log.info("springSecurity find codes = {}", codes);
            sysUser.setCodeList(codes);

            loginUserVO.setSysUser(sysUser);
            loginUserVO.setId(Long.valueOf(sysUser.getUserId()));
        }

        return loginUserVO;
    }
}
